package net.kazed.nextaction.context.activity;

import android.app.ListActivity;
import android.content.ContentUris;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;

import net.kazed.nextaction.R;
import net.kazed.nextaction.database.GtdContext;
import net.kazed.nextaction.database.Task;

public class InboxActivity extends ListActivity {

   private static final int MENU_INSERT_TASK = Menu.FIRST;
   
   private static final int NEW_TASK = 1;
   private static final int VIEW_TASK = 2;

	@Override
    public void onCreate(Bundle icicle) {
      setContentView(R.layout.inbox);
      setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT);

      Cursor cursor = managedQuery(Task.CONTENT_URI, Task.FULL_PROJECTION.getFieldNames(), Task.CONTEXT_ID + " = 0 or "
            + Task.CONTEXT_ID + " is null", null, Task.CREATED_DATE + " ASC");
      setListAdapter(new TaskListAdapter(this, cursor));

      super.onCreate(icicle);
	}
		
	@Override
	protected void onResume() {

		super.onResume();
	}

    @Override
   protected void onListItemClick(ListView l, View v, int position, long id) {
      Uri itemUri = ContentUris.withAppendedId(Task.CONTENT_URI, id);

      String action = getIntent().getAction();
      if (Intent.ACTION_PICK.equals(action) || Intent.ACTION_GET_CONTENT.equals(action)) {
         // The caller is waiting for us to return a task selected by
         // the user. They have clicked on one, so return it now.
         Intent intent = new Intent();
         setResult(RESULT_OK, intent);
      } else {
         // Launch activity to view/edit the currently selected item
         Intent intent = new Intent(Intent.ACTION_VIEW, itemUri);
         startActivityForResult(intent, VIEW_TASK);
      }
   }

    @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      Resources resources = getResources();
      menu.add(0, MENU_INSERT_TASK, 0, resources.getString(R.string.menu_add_task))
         .setIcon(android.R.drawable.ic_menu_add)
         .setAlphabeticShortcut('a');
      return super.onCreateOptionsMenu(menu);
   }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
       switch (item.getItemId()) {
       case MENU_INSERT_TASK:
          Uri itemUri = getContentResolver().insert(Task.CONTENT_URI, null);
          Intent intent = new Intent(Intent.ACTION_INSERT, itemUri);
//          Intent intent = new Intent(Intent.ACTION_INSERT, Task.CONTENT_URI);
          startActivityForResult(intent, NEW_TASK);
          break;
       }
       return super.onOptionsItemSelected(item);
    }

}
